package com.ccp.dev.form.controller;

import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.form.consts.FormConstants;
import com.ccp.dev.form.model.FormDef;
import com.ccp.dev.form.model.FormDefTree;
import com.ccp.dev.form.model.FormField;
import com.ccp.dev.form.model.FormTable;
import com.ccp.dev.form.service.FormDefService;
import com.ccp.dev.form.service.FormDefTreeService;
import com.ccp.dev.form.service.FormFieldService;
import com.ccp.dev.form.service.FormTableService;
import net.sf.json.JSONObject;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 自定义表单树结构设置 Controller
 *
 * @author chenjing
 */
@Controller
@RequestMapping(UrlConstants.PROJECT_ROOT + UrlConstants.PROJECT_MODULE_FORM + "/formDefTree")
@Action(ownermodel = SysAuditModelType.FORM_MANAGEMENT)
public class FormDefTreeController extends SysBaseController {

    @Resource
    private FormDefTreeService formDefTreeService;

    @Resource
    private FormDefService formDefService;

    @Resource
    private FormFieldService formFieldService;

    @Resource
    private FormTableService formTableService;

    /**
     * 添加或更新form_def_tree。
     *
     * @param formDefTree formDefTree
     * @return ResultData
     */
    @RequestMapping("/save")
    @ResponseBody
    @Action(description = "保存表单树结构设置",exectype = "添加或更新日志",detail = "保存表单树结构设置<#if success>成功<#else>失败</#if>")
    public ResultData save(@RequestBody FormDefTree formDefTree) {
        try {
            FormDefTree oldFormDefTree=formDefTreeService.getByFormKey(formDefTree.getFormKey());
            String msg="formDefTree.update.success";
            if(oldFormDefTree==null){
                msg="formDefTree.add.success";
            }
            formDefTreeService.save(formDefTree);
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess(msg);
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                return getResultDataError("别名已被使用：" + formDefTree.getFormDefId());
            }
            e.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("formDefTree.save.failure");
        }
    }

    /**
     * 根据表单主键查询相应的树结构预览数据
     * @param request request
     * @return ResultData
     */
    @RequestMapping("/show")
    @ResponseBody
    @Action(description = "查询表单树结构设置",exectype = "查询日志",detail = "查询表单树结构设置<#if success>成功<#else>失败</#if>")
    public ResultData show(HttpServletRequest request) {
        String formKey=RequestUtil.getString(request,"formKey");
        try {
            FormDefTree formDefTree = formDefTreeService.getByFormKey(formKey);
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("query.success", formDefTree);
        }catch (Exception e){
            e.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("query.failure");
        }

    }

    /**
     * 利用return Object 根据页面传的不同请求参数来返回不同对象
     *
     * @param request request
     * @return ResultData
     */
    @RequestMapping("/getObject")
    @ResponseBody
    @Action(description = "查询表单表数据、树结构设置数据、树节点数据",exectype = "查询日志",detail = "查询表单表数据、树结构设置数据、树节点数据<#if success>成功<#else>失败</#if>")
    public ResultData getObject(HttpServletRequest request) {

        String action=RequestUtil.getString(request, "action");
        String formKey=RequestUtil.getString(request, "formKey");
        try {
            // 根据formDefId获取表数据
            if (FormConstants.STR_FORM_TABLE.equals(action)) {
                FormDef formDef = formDefService.getDefaultVersionByFormKey(formKey);
                Map<String, Object> rtnMap = new HashMap<>(3);
                if (formDef != null) {
                    List<FormField> formFieldList = formFieldService.getByTableId(formDef.getTableId());
                    rtnMap.put("formName", formDef.getSubject());
                    rtnMap.put("formField", formFieldList);
                }
                SysAuditThreadLocalHolder.putParamerter("success",true);
                return getResultDataSuccess("query.success", rtnMap.size(), rtnMap);

            }
            // 根据主键获取formDefTree
            else if (FormConstants.STR_FORM_DEF_TREE.equals(action)) {
                FormDefTree formDefTree = formDefTreeService.getByFormKey(formKey);
                SysAuditThreadLocalHolder.putParamerter("success",true);
                return getResultDataSuccess("query.success", formDefTree);
            }
            // 获取json数据。
            else if (FormConstants.STR_JSON.equals(action)) {
                // 这个参数是在异步加载时会赋值进来的
                String id = RequestUtil.getString(request, "id");
                Map<String, Object> params = new HashMap<>(2);
                params.put("id", id);
                List<JSONObject> jsonObjectList = formDefTreeService.treeListJson(formKey, params);
                SysAuditThreadLocalHolder.putParamerter("success",true);
                return getResultDataSuccess("query.success", jsonObjectList.size(), jsonObjectList);
            }
            return getResultDataError("query.failure");
        }catch (Exception e) {
            e.printStackTrace();
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("query.failure");
        }
    }

    /**
     * 树结构预览跳转
     * 由于当前路径是formDefTree 而页面所在路径为formDef 需要进行路径处理
     *
     * @return 页面路径
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/treePreview")
    @Action(description = "表单树结构预览页面跳转",exectype = "页面跳转日志")
    public String formDefTreeViewPreView(HttpServletRequest request,ModelMap modelMap) {
        String formKey=RequestUtil.getString(request,"formKey");
        //根据formKey查询table是否为版本控制
        Integer needVer = formDefService.getNeedVerByFormKey(formKey);
        //查找表名
        FormDef formDef = formDefService.getDefaultVersionByFormKey(formKey);
        FormTable formTable = formTableService.getOneById(formDef.getTableId());
        String tableName = formTable.getTableName();
        modelMap.put("tableName", tableName);
        modelMap.put("needVer", needVer);
        modelMap.put("formKey",formKey);
        return "form/formDef/treePreview";
    }

}
